package com.jack.cms.ueditor.upload;

import java.util.Map;

import org.apache.commons.codec.binary.Base64;

import com.jack.cms.core.util.SpringContextHolder;
import com.jack.cms.oss.core.QiniuUtils;
import com.jack.cms.ueditor.define.AppInfo;
import com.jack.cms.ueditor.define.BaseState;
import com.jack.cms.ueditor.define.FileType;
import com.jack.cms.ueditor.define.State;
import com.jack.cms.ueditor.define.UploadType;

public final class Base64Uploader {

	private static QiniuUtils getQiniuUtils(Map<String, Object> conf) {
		if (UploadType.MEDIA.equals(conf.get("type"))) {
			return SpringContextHolder.getBean("qiniuImageUtils");
		} else {
			return SpringContextHolder.getBean("qiniuFileUtils");
		}
	}

	public static State save(String content, Map<String, Object> conf) {

		byte[] data = decode(content);
		long maxSize = ((Long) conf.get("maxSize")).longValue();
		if (!validSize(data, maxSize)) {
			return new BaseState(false, AppInfo.MAX_SIZE);
		}
		QiniuUtils qiniuImageUtils = getQiniuUtils(conf);

		String originFileName = null;
		String fileName;
		try {
			String suffix = FileType.getSuffix("JPG");
			fileName = qiniuImageUtils.upload(content, originFileName);
			State state = new BaseState(true);
			state.putInfo("size", -1);
			state.putInfo("title", fileName);
			state.putInfo("url", qiniuImageUtils.getUrl(fileName));
			state.putInfo("type", suffix);
			state.putInfo("original", originFileName + suffix);
			return state;
		} catch (Exception e) {
			return new BaseState(false, AppInfo.IO_ERROR);
		}
	}

	private static byte[] decode(String content) {
		return Base64.decodeBase64(content);
	}

	private static boolean validSize(byte[] data, long length) {
		return data.length <= length;
	}

}